import { LdrsLoader } from "@renderer/components/business/ldrs-loader";
import { SidebarItem } from "@renderer/components/ui/base/sidebar";
import { cn } from "@renderer/lib/utils";
import { useThreadWithMessagesStatus } from "@renderer/queries/hooks/use-threads";
import type { Thread } from "@shared/triplit/types";
import { useCallback, useMemo } from "react";
import { ThreadMenu } from "./thread-menu";

interface ThreadItemProps {
  id: string;
  thread: Thread;
  isCurrent: boolean;
  onThreadClick: (id: string) => void;
}

export function ThreadItem({
  id,
  isCurrent,
  onThreadClick,
  thread,
}: ThreadItemProps) {
  const { data: status } = useThreadWithMessagesStatus(id);

  const pending = status === "pending";

  const displayTrigger = useMemo(
    () => (thread.collected ? "always" : "hover"),
    [thread.collected],
  );

  const handleClick = useCallback(() => onThreadClick(id), [onThreadClick, id]);

  return (
    <SidebarItem
      className={cn(
        "group flex h-10 cursor-pointer rounded-[10px] px-0 pr-2 pl-3 hover:bg-secondary [&_.text-muted-fg]:text-muted-fg",
        isCurrent &&
          "bg-accent text-accent-fg hover:bg-accent hover:text-accent-fg",
      )}
      key={id}
      isCurrent={isCurrent}
      onClick={handleClick}
    >
      {pending && <LdrsLoader type="line-spinner" size={16} stroke={1} />}
      <ThreadMenu
        thread={thread}
        isCurrent={isCurrent}
        displayTrigger={displayTrigger}
      />
    </SidebarItem>
  );
}
